package xsource

import (
	"time"

	"gitee.com/xiaoyutab/xgotool/optional/xcache"
	"gitee.com/xiaoyutab/xgotool/optional/xlog"
	"gitee.com/xiaoyutab/xgotool/optional/xnsq"
	"gitee.com/xiaoyutab/xgotool/xerror"
	"gitee.com/xiaoyutab/xgotool/xgodb"
)

// 根据商品code/id查询批次商品信息
//
//	id		商品ID
//	code	商品唯一code
//	msg		操作备注
//	ua		操作客户端的UserAgent
//	ip		操作客户端的IP地址
//	is_find	操作类型 0-内部流转 1-查询 2-产品作废
func InfoGoods(id uint64, code, msg, ua, ip string, is_find uint8) (*SourceChild, error) {
	if id == 0 && code == "" {
		return nil, xerror.New("参数传输错误")
	}
	sou := &SourceChild{}
	var err error
	if id > 0 {
		sou, err = info_goods_id(id)
	} else {
		sou, err = info_goods_code(code)
	}
	if err == nil {
		xnsq.Set("xsource.find", SourceLog{
			SourceChildId: sou.ID,
			Ip:            xgodb.KvId(ip),
			Msg:           msg,
			IsFind:        is_find,
			UserAgent:     xgodb.KvId(ua),
			CreatedAt:     time.Now().Format(time.DateTime),
		})
	}
	return sou, err
}

// 根据ID查询商品信息
func info_goods_id(id uint64) (*SourceChild, error) {
	cache_key := xcache.Key("xsource.info_goods_id", id)
	sou := SourceChild{}
	if xcache.Exists(cache_key) {
		if err := xcache.GetStruct(cache_key, &sou); err == nil {
			return &sou, nil
		}
	}
	// 数据库查询，并加入缓存
	err := _default.DB.Table(_default.SourceChildName).Where("id", id).Find(&sou).Error
	if err != nil {
		return nil, xlog.AE("溯源商品查询错误", err)
		return nil, err
	}
	xcache.SetStruct(cache_key, sou)
	return &sou, nil
}

// 根据code查询商品
func info_goods_code(code string) (*SourceChild, error) {
	cache_key := xcache.Key("xsource.info_goods_code", code)
	sou := SourceChild{}
	if xcache.Exists(cache_key) {
		if err := xcache.GetStruct(cache_key, &sou); err == nil {
			return &sou, nil
		}
	}
	// 数据库查询，并加入缓存
	err := _default.DB.Table(_default.SourceChildName).Where("goods_code", code).Find(&sou).Error
	if err != nil {
		return nil, xlog.AE("溯源商品查询错误", err)
	}
	xcache.SetStruct(cache_key, sou)
	return &sou, nil
}
